import React, { useState } from 'react';
import { Upload, message, Button, Modal } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';

export default function Test() {
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);

  const props = {
    name: 'image',
    accept: '.jpg,.png,.jpeg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    listType: 'picture-card',
    maxCount: '3',
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success('上传成功');
      } else if (info.file.status === 'error') {
        message.error('上传失败');
      }
    },
    onPreview(file) {
      //   console.log(file);
      //将图片地址存储
      setImgUrl(file.thumbUrl);
    },
    beforeUpload(file, fileList) {
      const allow = ['image/png', 'image/jpg', 'image/jpeg'];
      if (!allow.includes(file.type)) {
        message.warning('请上传jpg/png/jpeg的文件类型');
        return Upload.LIST_IGNORE;
      }
      console.log('file', file, fileList);
    },
  };
  return (
    <>
      <Upload {...props} fileList={fileList}>
        {fileList.length < 3 && <Button icon={<UploadOutlined />}></Button>}
      </Upload>
      <Modal
        visible={!!imgUrl}
        onCancel={() => {
          setImgUrl('');
        }}
        onOk={() => {
          setImgUrl('');
        }}
      >
        <img src={imgUrl} alt="" />
      </Modal>
    </>
  );
}
